from django import forms
from django.contrib.auth import get_user_model
from .models import VerificationModel

User = get_user_model()

class RegisterForm(forms.Form):
    username = forms.CharField(max_length=20,min_length=2,error_messages={
        'required': '请传入用户名',
        'max_length': '用户名长度在2~20之间',
        'min_length': '用户名长度在2~20之间',
    })
    email = forms.EmailField(error_messages={
        'required': '请传入邮箱',
        'invalid': '邮箱格式不正确',
    })
    password = forms.CharField(max_length=20,min_length=6,error_messages={
        'required': '请传入密码',
    })
    verification = forms.CharField(max_length=4,min_length=4,error_messages={
        'required': '请传入验证码',
    })

    def clean_email(self):
        email = self.cleaned_data.get('email')
        # TODO: 检查邮箱是否已经注册
        exists = User.objects.filter(email=email).exists()
        if exists:
            raise forms.ValidationError('邮箱已注册')
        return email

    def clean_verification(self):
        verification = self.cleaned_data.get('verification')
        email = self.cleaned_data.get('email')
        eval_model = VerificationModel.objects.filter(email=email,verification=verification).first()
        if not eval_model:
            raise forms.ValidationError('验证码错误')
        eval_model.delete()
        return verification

class LoginForm(forms.Form):
    email = forms.EmailField(error_messages={
        'required': '请传入邮箱',
        'invalid': '邮箱格式不正确',
    })
    password = forms.CharField(max_length=20, min_length=6, error_messages={
        'required': '请传入密码',
    })
    remember = forms.IntegerField(required=False)